<!-- 添加与修改组件SPU -->
<template>
  <el-form label-width="100px" status-icon>
    <el-form-item label="SPU名称" prop="spuName">
      <el-input v-model="userSpu.upDataSpu.spuName" />
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select
        v-model="userSpu.upDataSpu.tmId"
        placeholder="Select"
        size="large"
      >
        <el-option
          v-for="item in userSpu.allMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述" prop="description">
      <el-input type="textarea" v-model="userSpu.upDataSpu.description" />
    </el-form-item>
    <el-form-item label="SPU照片" prop="name">
      <el-upload
        v-model:file-list="userSpu.spuImg"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :before-upload="beforeAvatarUpload"
        :on-success="successAvatarUpload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        v-model="salesName"
        :placeholder="`还有${comSales.length}项未选择`"
        size="large"
      >
        <el-option
          v-for="item in comSales"
          :key="item.id"
          :label="item.name"
          :value="`${item.name}:${item.id}`"
        />
      </el-select>
      <el-button
        type="primary"
        style="margin-left: 10px; height: 40px"
        :disabled="salesName ? false : true"
        @click="addSalesAttr"
      >
        +添加销售属性
      </el-button>
      <el-table :data="userSpu.saleList" style="width: 100%" :border="true">
        <el-table-column type="index" label="序号" />
        <el-table-column prop="saleAttrName" label="属性名" />
        <el-table-column label="属性值">
          <template #default="scope">
            <el-tag
              style="margin: 0 5px"
              v-for="(item, $index) in scope.row.spuSaleAttrValueList"
              :key="item.id"
              closable
              @close="scope.row.spuSaleAttrValueList.splice($index, 1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="scope.row.inputSaleVisible == true"
              ref="InputRef"
              v-model="inputSaleValue"
              @keyup.enter="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            />
            <el-button v-else @click="showInput(scope.row)">
              + New Tag
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <!-- 删除 -->
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                icon="DeleteFilled"
                circle
                @click="userSpu.saleList.splice(scope.$index)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
  </el-form>
  <!-- 图片预览 -->
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup lang="ts">
import type { saleData } from '@/apis/goods/spu/spuTypes'
import { onMounted, nextTick, ref, computed } from 'vue'
import { ElMessage, UploadProps, ElInput } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'

/* 获取SPU仓库 */
import { userSpuState } from '@/store/goods/spu'
const salesName = ref('') /* 销售属性选中的值 */
const inputSaleValue = ref('') /* 添加销售属性输入的值 */
const InputRef = ref<InstanceType<typeof ElInput>>() /* 输入框Dom元素 */
/* 图片预览 */
const dialogImageUrl = ref('') /* 预览图片地址 */
const dialogVisible = ref(false) /* 预览弹窗 */
/* Spu模块仓库 */
const userSpu = userSpuState()
/* 组件一创建完就执行的逻辑 */
onMounted(() => {
  /* 获取全部品牌SPU*/
  userSpu.getAllSpu()
  /* 获取整个项目全部的销售属性[颜色、版本、尺码] */
  userSpu.getAllSalesAttr()
})
/* 上传图片前就行文件约束 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgTit = ['image/png', 'image/jpeg']
  if (!imgTit.includes(rawFile.type)) {
    ElMessage.error('请上传JPG格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传文件大小不能超过2MB')
    return false
  }
  return true
}
/* 上传图片成功后的钩子函数 */
const successAvatarUpload: UploadProps['onSuccess'] = (raeFile) => {
  /* 判断是否成功 */
  if (raeFile.code != 200) ElMessage.error(raeFile.message)
}
/* 删除图片 */
const handleRemove: UploadProps['onRemove'] = () => {
  ElMessage.success('删除成功')
}
/*查看图片 */
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
/* 添加属性按钮点击时触发 */
const addSalesAttr = () => {
  /* 查看 属性选折起有没有值 */
  if (!salesName.value) ElMessage.error('请选择销售数据类型')
  /* 有数据的话就进行添加 */
  /* 添加的属性  saleAttrName属性名 baseSaleAttrId id*/
  const [saleAttrName, baseSaleAttrId] = salesName.value.split(':')
  /* 创建新的销售数据进行接受 */
  let newSaleList: saleData = {
    saleAttrName /* 名称 */,
    baseSaleAttrId /* 选择的属性 iD*/,
    spuSaleAttrValueList: [],
  }
  userSpu.saleList.push(newSaleList)
  /* 添加完成清空输入框 */
  salesName.value = ''
}
/*Tag 添加属性值时显示 输入框 */
const showInput = (val: saleData) => {
  val.inputSaleVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}
/* 输入框失去焦点或者按下回车键时触发 确认添加 */
const handleInputConfirm = (val: saleData) => {
  val.inputSaleVisible = false
  if (!inputSaleValue.value) {
    ElMessage.error('输入数据后再进行操作')
    return
  }
  const saleFlag = val.spuSaleAttrValueList.every(
    (item) => item.saleAttrValueName != inputSaleValue.value,
  )
  if (!saleFlag) {
    ElMessage.error('该数据已经存在请重新输入')
    inputSaleValue.value = ''
    return
  }
  val.spuSaleAttrValueList.push({
    baseSaleAttrId: val.baseSaleAttrId as string,
    saleAttrName: val.saleAttrName,
    saleAttrValueName: inputSaleValue.value,
  })
  inputSaleValue.value = ''
}
/* 计算当前SPU还有几个属性未添加 */
const comSales = computed(() => {
  /* 全部销售属性 userSpu.allSalesAttr  版本，颜色，尺码 */
  /* 已有 版本，颜色，*/
  let unSelectArr = userSpu.allSalesAttr.filter((item) => {
    return userSpu.saleList.every((item1) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectArr
})
</script>

<style></style>
